<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Visit;

class Tongji extends Controller{
    //
    public function index(){
        if(!$this->request->isPost()){
            return json(['msg' => 'err']);
        }
        $vcid = $this->request->post('vcid', 0);
        if($vcid == 0){
            return json(['msg' => 'err']);
        }
        $position = $this->request->post('position', 0);
        $this->save($vcid, $position);
        return json(['msg' => 'ok']);
    }
    //
    public function send(){
        if(!$this->request->isPost()){
            return json(['msg' => 'err']);
        }
        $aid = $this->request->post('aid/d', 0);
        if($aid == 0){
            return json(['msg' => 'err']);
        }
        $position = $this->request->post('position', 0);
        $Visit = Visit::instance();
        $vcid = $Visit->sum($aid);
        if($position == 1){
            $agent = $this->request->header('user-agent', '');
            $tname = db('advert')->where('aid', '=', $aid)->value('tname', '');
            $url = $this->request->server('http_referer', '');
            $log = ['tname'=>$tname, 'ip'=>ip(), 'url'=>$url, 'agent'=>$agent, 'vcid'=>$vcid];
            $Visit->log($log);
        }
        $this->save($vcid, $position);
        return json(['msg' => 'ok']);
    }
    //
    private function save($vcid, $position){
        switch($position){
            case 1:
                db('visit_count')->where('vcid', '=', $vcid)->inc('top')->update();
                break;
            case 2:
                db('visit_count')->where('vcid', '=', $vcid)->inc('middle')->update();
                break;
            case 3:
                db('visit_count')->where('vcid', '=', $vcid)->inc('bottom')->update();
                break;
            default:
                break;
        }
    }
}